package com.example.leetdemo.finash;

import java.util.ArrayList;
import java.util.List;

public class Solution1592 {
    public String reorderSpaces(String text) {
        int count = text.length() - text.replace(" ", "").length();
        List<String> words = new ArrayList<>();
        String[] strs = text.split(" ");
        for(int i = 0; i < strs.length; i++) {
            if(!strs[i].equals("")) {
                words.add(strs[i]);
            }
        }
        StringBuilder builder = new StringBuilder();
        builder.append(words.get(0));
        if (words.size() != 1) {
            int step = count / (words.size() - 1);
            for(int i = 1; i < words.size(); i++) {
                for(int j = 0; j < step; j++) {
                    builder.append(" ");
                    count--;
                }
                builder.append(words.get(i));
            }
        }
        for(int i = 0; i < count; i++) {
            builder.append(" ");
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        Solution1592 solution1592 = new Solution1592();
        System.err.println(solution1592.reorderSpaces("  this   is  a sentence "));
    }
}
